#pragma once
#include <Windows.h>
#include <string>

#include "PipeListener.h"
#include "PipeMessage.h"

using namespace std;
class Connection
{
	string mDescription;
	string mPipeName;
	bool mIsServer;
	bool mIsOnline;

	HANDLE mPipe;
	HANDLE mWriteMessageSem;

	int mInputSize;
	int mOutputSize;
	int mTimeout;

	HANDLE mListenThread;
	DWORD mListenThreadId;

	bool mTerminateServer;

	SECURITY_ATTRIBUTES mSA;


	OVERLAPPED mOvl;

private:
	bool CreatePipe();
	bool Connect();
	void Disconnect();
	bool GetOnline();
	bool CreateSecurityDescriptor();



	static DWORD WINAPI WaitForMessages(LPVOID param);

public:
	Connection(string _name, string _pipeName, bool _server);
	~Connection(void);

	void Listen(PipeListener* _listener);
	bool Write(BYTE* _data, int _size);
	bool SendMessage(PipeMessage* _msg);

	void ChangeSettings(int _inBuffSize, int _outBuffSize, int _timeout);


	bool IsOnline() const;
	const string& Description() const;
	const string& PipeName() const;
	HANDLE GetPipe() const { return mPipe; }

	string PipeNameAsIp();
};

